package com.hfb.mashibing.alip8.jvm.asm;

import static org.objectweb.asm.Opcodes.ACC_ABSTRACT;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_INTERFACE;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_STATIC;
import static org.objectweb.asm.Opcodes.V1_5;

import org.objectweb.asm.ClassWriter;
/**
 * asm可以动态生成字节码文件—— .class 文件
 */
public class ClassWriterTest {
    public static void main(String[] args) {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(V1_5, ACC_PUBLIC+ACC_ABSTRACT + ACC_INTERFACE,
                "pkg/Comparable", null, "java/lang/Object",
                null);
        cw.visitField(ACC_PUBLIC+ACC_FINAL + ACC_STATIC, "LESS", "I",
                    null, -1).visitEnd();
        cw.visitField(ACC_PUBLIC+ACC_FINAL + ACC_STATIC, "EQUAL", "I",
                    null, -1).visitEnd();
        cw.visitField(ACC_PUBLIC+ACC_FINAL + ACC_STATIC, "EGREATER", "I",
                    null, -1).visitEnd();
        cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, "compareTo", "(Ljava/lang/Object;)I)",
                    null,null).visitEnd();
        cw.visitEnd();
        byte[] b = cw.toByteArray();

        MyClassLoader myClassLoader = new MyClassLoader();
        Class c = myClassLoader.defineClass("pkg.comparable", b);
        System.out.println(c.getMethods()[0].getName());
    }
    static class MyClassLoader extends ClassLoader {
        public Class defineClass(String name,byte[] bs) {
            return defineClass(name,bs,0,bs.length);
        }
    }
}

